﻿
namespace __Able.Network.Threading
{
    public class KeepAliveTrigger : IRunable
    {
        private Channel channel;
        /// <summary>
        /// 单位: ms
        /// </summary>
        private const int INTERVAL_KEEP_ALIVE = 5000;

        public KeepAliveTrigger(Channel channel)
        {
            this.channel = channel;
            ThreadExcutor.RegisterIntervalObject(this, this, INTERVAL_KEEP_ALIVE, false);
        }

        public bool IsRunning
        {
            get;
            private set;
        }

        public void Run(object state, bool timedOut)
        {
            if (!IsRunning)
            {
                lock (this)
                {
                    if (!IsRunning)
                    {
                        IsRunning = true;
                        this.channel.KeepAliveManager.KeepAlive();
                        IsRunning = false;
                    }
                }
            }

        }
        public System.Threading.WaitHandle WaitHandler
        {
            get;
            set;
        }
        public System.Threading.RegisteredWaitHandle RegisterdHandler
        {
            get;
            set;
        }
        public void Dispose()
        {
            if (this.WaitHandler != null && this.RegisterdHandler != null)
            {
                RegisterdHandler.Unregister(this.WaitHandler);
            }
        }
    }
}
